package com.atech.ebayadmin.inter.service;

import com.ebay.sdk.ApiAccount;
import com.ebay.sdk.ApiContext;
import com.ebay.sdk.ApiCredential;
import com.ebay.sdk.ApiLogging;
import com.ebay.sdk.CallRetry;
import com.ebay.sdk.call.AddItemCall;
import com.ebay.sdk.call.GetAccountCall;
import com.ebay.sdk.call.GetCategoriesCall;
import com.ebay.sdk.call.VerifyAddItemCall;
import com.ebay.soap.eBLBaseComponents.AccountEntryType;
import com.ebay.soap.eBLBaseComponents.AccountHistorySelectionCodeType;
import com.ebay.soap.eBLBaseComponents.CategoryType;
import com.ebay.soap.eBLBaseComponents.DetailLevelCodeType;
import com.ebay.soap.eBLBaseComponents.FeesType;
import com.ebay.soap.eBLBaseComponents.ItemType;
import com.ebay.soap.eBLBaseComponents.SiteCodeType;
import com.atech.ebayadmin.inter.IEbayService;
import com.atech.ebayadmin.system.model.SystemConfig;
import com.atech.ebayadmin.system.service.ISystemService;

//import org.w3c.dom.Document;
//import org.w3c.dom.Node;

public class EbayService implements IEbayService{
	
	public static final String CONFIG_XML_NAME = "eBay_Config.xml";
	private ApiLogging apiLogging = new ApiLogging();
	private CallRetry callRetry = new CallRetry();
	private ApiContext apiContext = new ApiContext();	
	private ISystemService systemService;

	public CategoryType[] getCategoriesCall(String token)throws Exception{
		this.createApiContext(token);
		CategoryType[] Categories=null;
		try{
			GetCategoriesCall api=new GetCategoriesCall(this.apiContext);
			api.setDetailLevel(new DetailLevelCodeType[] { DetailLevelCodeType.RETURN_ALL});
			//api.setLevelLimit(2);
			api.setCategorySiteID(SiteCodeType.US);
			api.setParentCategory(new String [] {"293"} );			//Electronics			
			api.setViewAllNodes(true);
			// for further disccusion with hellen
			//int test=GetCategoriesCall.getAllCategories(this.apiContext, 0, 0, DetailLevelCodeType.RETURN_ALL, 0, null);
			Categories=api.getCategories();	
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
			Categories = null;
		}
		return Categories;
	}
	
	public AccountEntryType[] getAccountCall(String token)  throws Exception{
		this.createApiContext(token);
		AccountEntryType[] entries = null;
		GetAccountCall api = new GetAccountCall(this.apiContext);
		api.setDetailLevel(new DetailLevelCodeType[] { DetailLevelCodeType.RETURN_ALL});
		AccountHistorySelectionCodeType ht = AccountHistorySelectionCodeType.LAST_INVOICE;
		api.setViewType(ht);
	    entries = api.getAccount();	
		return entries;
	}
	
	public FeesType verifyAddItemCall(String token,ItemType item, String[] pictureFiles)  throws Exception{
		this.createApiContext(token);
		FeesType fees = null;	
		VerifyAddItemCall api = new VerifyAddItemCall(apiContext);
		api.setItem(item);
		api.setPictureFiles(pictureFiles);
		fees = api.verifyAddItem();
		return fees;
	}
	
	public FeesType addItemCall(String token,ItemType item, String[] pictureFiles) throws Exception{
		this.createApiContext(token);
		FeesType fees = null;
		AddItemCall api = new AddItemCall(apiContext);
		api.setItem(item);
		api.setPictureFiles(pictureFiles);
		fees = api.addItem();	
		return fees;
	}
	
	public void createApiContext(String token)throws Exception{		
		try{
			// Turn on logging.
			apiContext.setApiLogging(this.apiLogging);
			// Enable Call-Retry.
			this.callRetry.setMaximumRetries(3);
			this.callRetry.setDelayTime(1000); // Wait for one second between each retry-call.
			String[] apiErrorCodes = new String[] {
					"10007", // "Internal error to the application."
					"931", // "Validation of the authentication token in API request failed."
					"521", // Test of Call-Retry: "The specified time window is invalid."
					"124" // Test of Call-Retry: "Developer name invalid."
			};
			this.callRetry.setTriggerApiErrorCodes(apiErrorCodes);

			// Set trigger exceptions for CallRetry.
			// Build a dummy SdkSoapException so that we can get its Class.
			java.lang.Class[] tcs = new java.lang.Class[] {
	          com.ebay.sdk.SdkSoapException.class
			};
	    
			// Set Call-Retry.
			this.callRetry.setTriggerExceptions(tcs);
			apiContext.setCallRetry(this.callRetry);
			apiContext.setTimeout(180000);	    
			SystemConfig systemConfig = systemService.getSystemConfig();
			this.loadConfiguration( systemConfig.getAppId(),
									systemConfig.getAppId(),
									systemConfig.getCertId(),
									token);
			// temp
			apiContext.setSite(SiteCodeType.US);
		}catch (Exception e) {
		    e.printStackTrace();
		    throw new Exception("获取Ebay连接上下文失败");
		}
	}
	
	public void loadConfiguration( String devId, String appId, String certId, String token) throws Exception
	{
		/*String xmlPath = CONFIG_XML_NAME;
	    Document doc = XmlUtil.createDomByPathname(xmlPath);//getConfigXmlText()

	    Node config = XmlUtil.getChildByName(doc, "Configuration");
	    if( config == null )
	      throw new Exception("<Configuration> was not found.");
		*/
	    String s;

	    //s = XmlUtil.getChildString(config, "ServerUrl").trim();
	   
//	    apiContext.setApiServerUrl("https://api.ebay.com/wsapi");
//	    apiContext.setEpsServerUrl("https://api.ebay.com/ws/api.dll");
//	    apiContext.setSignInUrl("https://signin.ebay.com/ws/eBayISAPI.dll?SignIn");
	    
	    //s = XmlUtil.getChildString(config, "EpsServerUrl").trim();
	    apiContext.setApiServerUrl("https://api.sandbox.ebay.com/wsapi");
	    apiContext.setEpsServerUrl("https://api.sandbox.ebay.com/ws/api.dll");
	    apiContext.setSignInUrl("https://signin.sandbox.ebay.com/ws/eBayISAPI.dll?SignIn");
	   
	    
	    //s = XmlUtil.getChildString(config, "SignInUrl").trim();
	    
	   

	    //String logFilePath = XmlUtil.getChildString(config, "LogFilePath").trim();
	    /// @TODO this.initializeLogger(logFilePath);

	    ApiCredential apiCred = new ApiCredential();
	    ApiAccount ac = new ApiAccount();
	    ac.setDeveloper(devId);
	    ac.setApplication(appId);
	    ac.setCertificate(certId);
	    apiCred.setApiAccount(ac);
	    apiCred.seteBayToken(token.trim());
	    apiContext.setApiCredential(apiCred);
	    
	    //


	    //Node eBayCredential = XmlUtil.getChildByName(config, "eBayCredential");

	    //s = XmlUtil.getChildString(eBayCredential, "Token");

	    
	    //s=XmlUtil.getChildString(config,"RuName");
	    /*if(s.length() > 0){
	    	apiContext.setRuName(s);
	    }*/
	    
	    /*s = XmlUtil.getChildString(config, "Timeout");
	    if (s.length() > 0)
	    {
	      int timeout = Integer.parseInt(s);
	      apiContext.setTimeout(timeout);
	    }*/
	}
	/**
	 * @return the systemService
	 */
	public ISystemService getSystemService() {
		return systemService;
	}

	/**
	 * @param systemService the systemService to set
	 */
	public void setSystemService(ISystemService systemService) {
		this.systemService = systemService;
	}
}
